package com.miyake.loveviewweb.client.viewer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.appengine.api.datastore.Key;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.miyake.loveviewweb.client.DataServiceWrapper;
import com.miyake.loveviewweb.client.chart.IChart;
import com.miyake.loveviewweb.client.chart.LvChartFactory;
import com.miyake.loveviewweb.client.chart.StaticChart;
import com.miyake.loveviewweb.client.chart.StaticChart.StaticChartHandler;
import com.miyake.loveviewweb.client.dialog.BasicDialog;
import com.miyake.loveviewweb.client.dialog.DialogHandler;
import com.miyake.loveviewweb.client.dialog.IDialogPanel;
import com.miyake.loveviewweb.shared.model.ChartModel;
import com.miyake.loveviewweb.shared.model.ChartModel.ChartEngine;
import com.miyake.loveviewweb.shared.model.PluginModel;

public class ChartListWidget extends AbstractListWidget<ChartModel> {
    @Override
    public void setColumns(Integer columns) {
        chartTool.setColumns(columns);
        super.setColumns(columns);
    }

    protected List<IChart> chartWidgets = new ArrayList<IChart>();
    protected Map<CheckBox, Key> checkBoxes = new HashMap<CheckBox, Key>();
    protected ChartToolbar chartTool;
   
    protected void onColumnCountChange(int column) {}
    
    protected Widget getAdditionalTool() {
        return new HTML("");
    }
    
    @Override
    protected Widget getHeader() {
        chartTool = new ChartToolbar() {

            @Override
            void onColumnsChange(Integer column) {
                onColumnCountChange(column);
                ChartListWidget.this.setColumns(column);

            }

            @Override
            void onChartTypeChange(final String chartType, PluginModel pluginModel) {
                List<Key> keys = new ArrayList<Key>();
                for (ChartModel charts : getElements()) {
                    keys.add(charts.getKey());
                }

                ChartEngine chartEngine = null;

                if (chartType.equals(FLASH_CHART)) {
                    chartEngine = ChartEngine.DEFAULT_FLASH_CHART;
                }
                else if (chartType.equals(SIMPLE_DYNAMIC_CHART)) {
                    chartEngine = ChartEngine.DEFAULT_DYNAMIC_CHART;
                }
                else  {
                    chartEngine = ChartEngine.PLUGIN_CHART;
                }
                Key pluginKey = null;
                if (pluginModel != null) {
                    pluginKey = pluginModel.getKey();
                }
                DataServiceWrapper.getInstance().getService().updateChartEngine(keys, chartEngine, pluginKey, new AsyncCallback<Void>() {

                    public void onFailure(Throwable caught) {
  
                    }

                    public void onSuccess(Void result) {
                        updateChartModels();
                    }
                            
                });

            }

            @Override
            void onChartSizeChange(final Integer width, final Integer height) {
                for (IChart chart : chartWidgets) {
                    chart.setChartSize(width, height);
                }
            }

            @Override
            void onEditEnabled(boolean enabled) {
                for (CheckBox c : checkBoxes.keySet()) {
                    c.setVisible(enabled);
                }
            }

            @Override
            void onDelete() {
                DataServiceWrapper.getInstance().delete(getSelectedKeys());
            }

        };
        
        chartTool.addWidget(getAdditionalTool());
        
        return chartTool;
    }

    
    public ChartListWidget(Key dataKey) {
        DataServiceWrapper.getInstance().getService().getChartList(dataKey, false, new AsyncCallback<List<ChartModel>>() {
            public void onFailure(Throwable caught) {
            }

            public void onSuccess(List<ChartModel> result) {
                setElements(result);
                update();
            }
        });
    }
    
    public ChartListWidget(List<ChartModel> charts) {
        setElements(charts);
        update();
    }
    
    @Override
    protected
    Widget getWidget(final ChartModel chartModel) {
        IChart chart = null;

        if (chartModel.getChartEngine().equals(ChartModel.ChartEngine.PLUGIN_CHART)) {
            chart = LvChartFactory.getInstance().createStaticChart(new StaticChartHandler() {
                public void onSelect(StaticChart chart) {
                    goDynamicChartWindow(chart, chartModel);
                }
            });
        }
        else if (chartModel.getChartEngine().equals(ChartModel.ChartEngine.DEFAULT_FLASH_CHART)) {
            chart = LvChartFactory.getInstance().createFlashChart();
        }
        else if (chartModel.getChartEngine().equals(ChartModel.ChartEngine.DEFAULT_DYNAMIC_CHART)) {
            chart = LvChartFactory.getInstance().createSimpleDynamicChart();
        }
        chartWidgets.add(chart);
        VerticalPanel panel = new VerticalPanel();
        CheckBox check = new CheckBox(chartModel.getName());
        check.setVisible(false);
        checkBoxes.put(check, chartModel.getKey());
        panel.add(check);
        panel.add(chart.getUiWidget());
        chart.setData(chartModel);
        
        // Test trial
//        panel.add(new HTML("<IFRAME SRC=\"" + GWT.getHostPageBaseURL() + "?startup=dynamicChartTest" + "\" NAME=\"Dynamic Chart\"></IFRAME>"));
//        panel.add(new HTML("<IFRAME SRC=\"http://127.0.0.1:8888/index.html?gwt.codesvr=127.0.0.1:9997&startup=dynamicChartTest" + "\" NAME=\"Dynamic Chart\"></IFRAME>"));

        
        return panel;
    }

    protected void goDynamicChartWindow(StaticChart chart, ChartModel chartModel) {
        DataServiceWrapper.getInstance().getService().keyToString(chartModel.getKey(), new AsyncCallback<String>() {

            public void onFailure(Throwable caught) {
                // TODO Auto-generated method stub
                
            }

            public void onSuccess(String result) {
                String url = GWT.getHostPageBaseURL() + "?startup=dynamicChartTest&key="+result;
              //  String url = "http://127.0.0.1:8888/index.html?gwt.codesvr=127.0.0.1:9997&startup=dynamicChartTest&key="+result;
              //  String s = "<IFRAME SRC=\"" + url +  "\" NAME=\"Dynamic Chart\" width=600 height=400></IFRAME>";
                Window.open(url, "", "");
            }
            
        });
    }
    
    protected void showDynamicChartDialog(StaticChart chart, final ChartModel chartModel) {
        
        class FlashChartComposite extends Composite implements IDialogPanel {
            public FlashChartComposite() {
                final HTML html = new HTML();
                DataServiceWrapper.getInstance().getService().keyToString(chartModel.getKey(), new AsyncCallback<String>() {

                    public void onFailure(Throwable caught) {
                        // TODO Auto-generated method stub
                        
                    }

                    public void onSuccess(String result) {
                      String url = GWT.getHostPageBaseURL() + "?startup=dynamicChartTest&key="+result;
                      //  String url = "http://127.0.0.1:8888/index.html?gwt.codesvr=127.0.0.1:9997&startup=dynamicChartTest&key="+result;
                        String s = "<IFRAME SRC=\"" + url +  "\" NAME=\"Dynamic Chart\" width=600 height=400></IFRAME>";
                        html.setHTML(s);
                    }
                    
                });
                

                
                initWidget(html);
            }
            
            public void setDialogHandler(DialogHandler handler) {

            }

            public Composite getComposite() {
                return this;
            }
            
        };
        
        new BasicDialog(new FlashChartComposite()) {
            @Override
            protected void onOK(Composite composite) {
               
            }    
        }.showDialog();
    }

    protected void updateChartModels() {
      //  DataServiceWrapper.getInstance().getService().getC
        List<Key> keys = new ArrayList<Key>();
        for (ChartModel chartModel : this.getElements()) {
            keys.add(chartModel.getKey());
        }
        
        DataServiceWrapper.getInstance().getService().getChartList(keys, true, new AsyncCallback<List<ChartModel>>() {
            public void onFailure(Throwable caught) {
            }

            public void onSuccess(List<ChartModel> result) {
                setElements(result);
                update();
            }
            
        });
    }

    private List<Key> getSelectedKeys() {
        List<Key> keys = new ArrayList<Key>();
        for (CheckBox checkBox : checkBoxes.keySet()) {
            if (checkBox.getValue().equals(true)) {
                keys.add(checkBoxes.get(checkBox));
            }
        }
        return keys;
    }
}
